package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Ip;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.exception.LoginException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.IpMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.qo.UserContext;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.IPUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class EmployeeServiceImpl implements IEmployeeService {
    //private static final Logger log = LoggerFactory.getLogger(EmployeeServiceImpl.class);

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private IpMapper ipMapper;

    @Override
    public int insertEmployee(Employee record) {
        employeeMapper.insert(record);
        return 0;
    }

    @Override
    public int deleteEmployee(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
        employeeMapper.deleteEmpRoleMiddleTable(id);
        return 0;
    }

    @Override
    public int updateEmployee(Employee record) {
        return employeeMapper.updateByPrimaryKey(record);
    }


    @Override
    public Employee selectEmployee(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> selectEmployeeList() {
        return employeeMapper.selectAll();
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        log.info("==================名字{}=================", UserContext.getEmployee().getName());
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        return new PageInfo(employeeMapper.queryList(qo));
    }

    @Override
    public void saveEmpAndRole(Employee employee, Long[] roleIds) {
        employeeMapper.insert(employee);
        if (roleIds != null && roleIds.length != 0) {
            employeeMapper.insertEmpRoleMiddleTable(employee.getId(), roleIds);
        }
    }

    @Override
    public void updateEmpAndRole(Employee employee, Long[] roleIds) {
        employeeMapper.updateByPrimaryKey(employee);
        if (roleIds != null && roleIds.length != 0) {
            employeeMapper.deleteEmpRoleMiddleTable(employee.getId());
            employeeMapper.insertEmpRoleMiddleTable(employee.getId(), roleIds);
        }
    }

    @Override
    public Employee selectUserExists(String username, String password, HttpServletRequest request) {
        if (!StringUtils.hasText(username)) {
            throw new LoginException("用户名为空");
        }
        if (!StringUtils.hasText(password)) {
            throw new LoginException("密码为空");
        }

        //获取当前访问的Ip
        String ip = IPUtil.getIp(request);
        //通过获取的ip去数据库查询 之前有没有访问过
        Ip ipObj = ipMapper.selectIP(ip);

        Employee employee = null;


        //如果这个IP为空就是第一次访问 也要判断他密码是否正确
        if (ipObj == null) {
            employee = employeeMapper.selectUserExists(username, password);
            if (employee == null) {
                //第一次访问就创建一个IP对象
                Ip ip1 = new Ip();
                //把当前访问的ip存进去 和 访问次数为1
                ip1.setIp(ip);
                ip1.setCount(1);
                //把对象存到数据库
                ipMapper.insert(ip1);
                throw new LoginException("账号密码错误");
            }
        } else if (ipObj.getCount() == 6) {
            //要判断时间 如果超出两分钟就应该判断一下密码是否正确 把数据删除
            // 如果密码不正确 就跑密码错误异常
            // 正确的话 成员变量就有对象
            //获取冻结时间
            long time = ipObj.getNowtime().getTime();
            //获取当前时间
            long now = new Date().getTime();
            if (now - time > 10000) {
                employee = employeeMapper.selectUserExists(username, password);
                ipMapper.deleteIp(ipObj.getIp());
                if (employee == null) {
                    throw new LoginException("账号密码错误");
                }
            } else {
                //如果没有超出两分钟就不用判断直接抛冻结
                throw new LoginException("账号已被冻结");
            }
        } else if (ipObj.getCount() != 6 && ipObj != null) {
            //如果不等于6 和 不为null 就是登录过
            //也是需要先判断他是否密码错误
            employee = employeeMapper.selectUserExists(username, password);
            if (employee == null) {
                //如果密码错误 就获取一下 他错了多少次
                int count = ipObj.getCount();
                //如果小于5次就
                if (count < 5) {
                    //根据ip修改次count 将count 的次数 + 1
                    ipMapper.updateCount(ipObj.getIp(), count + 1);
                    //并抛出异常 账号错误
                    throw new LoginException("账号密码错误");
                }

                //如果等于5次就冻结 就抛出异常 被冻结
                if (count == 5) {
                    //设置当前时间
                    ipObj.setNowtime(new Date());
                    //把次数加成6
                    ipObj.setCount(count + 1);
                    ipMapper.update(ipObj);
                    throw new LoginException("账号已冻结,请稍后再试");
                }
            }
        }


        return employee;


    }

    @Override
    public List<String> selectEmployeePermission(Long empId) {
        List<String> permissions = employeeMapper.selectEmployeePermission(empId);
        return permissions;
    }

    @Override
    public Employee checkUserName(String username) {
        return employeeMapper.checkUserName(username);
    }


    @Override
    public Workbook exportXls(String keyWord, Long deptId) {
        List<Employee> employees = employeeMapper.exportXls(keyWord, deptId);
        //创建一个excel表格
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建表
        Sheet sheet = workbook.createSheet("员工通讯录");
        //创建行
        Row row = sheet.createRow(0);
        //通过行来指定列和值
        row.createCell(0).setCellValue("序号");
        row.createCell(1).setCellValue("用户名");
        row.createCell(2).setCellValue("真实姓名");
        row.createCell(3).setCellValue("邮箱");
        row.createCell(4).setCellValue("年龄");

        for (int i = 0; i < employees.size(); i++) {
            //通过遍历 获取每一个员工数据
            Employee employee = employees.get(i);
            //创建行 有多少条数据就有多少行
            Row row1 = sheet.createRow(i + 1);
            row1.createCell(0).setCellValue(employee.getId());
            row1.createCell(1).setCellValue(employee.getUsername());
            row1.createCell(2).setCellValue(employee.getName());
            row1.createCell(3).setCellValue(employee.getEmail());
            if (employee.getAge() != null) {
                row1.createCell(4).setCellValue(employee.getAge());
            }

        }
        return workbook;
    }

    @Override
    public List<String> importXls(MultipartFile file) throws IOException {

        //定义一个List来储存第几行错误和错误信息
        /*   Map<Integer, String> map = new TreeMap<>();*/
        List<String> list = new ArrayList<>();

        //把接收到的文件以excel的方式去读取并操作
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //获取第一页
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        //遍历表格中的每一行 除了第一行
        for (int i = 1; i <= lastRowNum; i++) {

            Employee employee = new Employee();
            //通过表获取每一行的数据
            Row row = sheet.getRow(i);

            String username = row.getCell(0).getStringCellValue();

            //如果查询到有用户名存在的就跳过这一次循环
            if (employeeMapper.checkUserName(username) != null) {
                String str = "第 " + i + "行,插入失败,用户名已存在";
                list.add(str);
                continue;
            }
            employee.setUsername(username);
            String name = row.getCell(1).getStringCellValue();
            employee.setName(name);
            String email = row.getCell(2).getStringCellValue();
            employee.setEmail(email);

            int age = (int) row.getCell(3).getNumericCellValue();
            if (age < 18 || age > 80) {
                String str = "第" + i + "行,插入失败,年龄超过范围";
                list.add(str);
                continue;
            }
            employee.setAge(age);
            employeeMapper.insert(employee);
        }
        String size = "共有" + (lastRowNum - list.size()) + "条数据插入成功";
        list.add(size);
        //System.out.println(list);
        return list;
    }

    @Override
    public void deleteInBatches(Long[] ids) {
        employeeMapper.deleteInBatches(ids);
    }

    @Override
    public void updatePassword(Long id, String password) {
        employeeMapper.updatePassword(id, password);
    }

    @Override
    public void updateStatus(Long id) {
        employeeMapper.updateStatus(id);
    }


}
